#-*- coding:utf-8 -*-

from django.http import HttpResponse, Http404
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.decorators.csrf import csrf_exempt
from django.utils import simplejson

from circle.models import Bang, Member, Topic
from circle.forms import CreateBangForm, AddTopicForm
from image import save_upload_image


TOPIC_NUM_OF_PAGE = 20
BANG_NUM_OF_PAGE = 20


def index(request):
    return render(request, "circle/index.html")

def latest_bang(request, page_num):
    _pagenum = int(page_num)
    bang_qs = Bang.objects.filter(status=Bang.STATUS_NORMAL)
    paginator = Paginator(bang_qs, BANG_NUM_OF_PAGE)

    try:
        bang_list = paginator.page(page_num)
    except EmptyPage:
        bang_list = paginator.page(paginator.num_pages)

    return render(request, "circle/bang_list.html", {'bang_list': bang_list, 'page':paginator})


def bang_detail(request, bang_id):
    _bangid = int(bang_id)
    bang = get_object_or_404(Bang, pk=_bangid)
    return render(request, "circle/bang_detail.html", {"bang": bang}) 

@login_required
def create_bang(request):
    if request.method == 'GET':
        f = CreateBangForm()
        return render(request, "circle/add_bang.html", {"form":f})
        
    f = CreateBangForm(request.POST)
    if f.is_valid():
        bang = f.save(False)
        bang.owner= request.user
        bang.save()

        for imgname in request.POST.getlist('userimg', []):
            setTopicImage(request.user, imgname, topic)

        return redirect("/circle/detail/%d/"%(bang.id))

    else:
        return render(request, "circle/add_bang.html", {"form":f})


def upload_bang_image(request):
    pass


@login_required
def bang_apply(request, bang_id):
    _bangid = int(bang_id)
    ret = {}
    qs = Member.objects.filter(user=request.user, bang__id = _bangid)
    if len(qs) != 0:
        ret['ret'] = 'fail';
        m = qs[0]
        if m.status == Member.STATUS_APPLY:
            ret['code'] = 'alreadyApplied'

        if m.status == Member.STATUS_NORMAL:
            ret['code'] = 'alreadyInCircle'

        return HttpResponse(simplejson.dumps(ret))

    _bangid = int(bang_id)
    bang = get_object_or_404(Bang, pk=_bangid)
    m = Member()
    m.user = request.user
    m.bang = bang
    m.save()

    ret['ret'] = 'ok'
    return HttpResponse(simplejson.dumps(ret))


@login_required
def bang_approve(request, bang_id, user_id):
    _bangid = int(bang_id)
    _userid = int(user_id)
    qs = Member.objects.filter(user__id = _userid, bang__id = _bangid)
    if len(qs) == 0:
        return HttpResponse(simplejson.dumps({'ret':'fail', 'err':'user not exists'}))

    m = qs[0]
    m.status = Member.STATUS_NORMAL
    return HttpResponse(simplejson.dumps({'ret':'ok'}))


@login_required
def add_topic(request, bang_id):
    _bangid = int(bang_id)
    bang = get_object_or_404(Bang, pk=bang_id)

    if request.method == 'GET':
        f = AddTopicForm()
        return render(request, "circle/add_topic.html", {"form":f, "bang":bang})
        
    f = AddTopicForm(request.POST)
    if f.is_valid():
        topic = f.save(False)
        topic.bang = bang
        topic.author = request.user
        topic.save()

        print request.POST
        save_upload_image(request, topic) 
        return redirect("/circle/%d/"%(bang.id))

    else:
        return render(request, "circle/add_topic.html", {"form":f, "bang":bang})


def latest_topic(request, page_num):
    _pagenum = int(page_num)
    topic_qs = Topic.objects.filter(status=Topic.STATUS_NORMAL)
    paginator = Paginator(topic_qs, TOPIC_NUM_OF_PAGE)

    try:
        topic_list = paginator.page(page_num)
    except EmptyPage:
        topic_list = paginator.page(paginator.num_pages)

    return render(request, "circle/topic_list.html", {'topic_list': topic_list, 'page':paginator})


def topic_list(request, bang_id, page_num):
    _bangid = int(bang_id)
    _pagenum = int(page_num)

    bang = get_object_or_404(Bang, pk=_bangid)
    topic_qs = Topic.objects.filter(status=Topic.STATUS_NORMAL, bang_id = _bangid)
    paginator = Paginator(topic_qs, TOPIC_NUM_OF_PAGE)

    try:
        topic_list = paginator.page(page_num)
    except EmptyPage:
        topic_list = paginator.page(paginator.num_pages)

    return render(request, "circle/topic_list.html", {'topic_list': topic_list, 'page':paginator,'bang':bang})


def topic_detail(request, topic_id):
    _topicid = int(topic_id)
    topic = get_object_or_404(Topic, pk=_topicid)
    topic.reads = topic.reads + 1
    topic.save()
    return render(request, "circle/topic_detail.html", {"topic": topic}) 


